package com.laowang.project.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.web.page.TableDataInfoMy;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.mapper.SysRoleMapper;
import com.laowang.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

/**
 * 商家团购产品Controller
 *
 * @author laowang
 * @date 2023-07-24
 */
@Api(tags = "商家团购产品接口")
@RestController
@RequestMapping("/shopProduct")
public class MyCyhShopProductController extends BaseController {
    @Autowired
    private MyCyhShopProductService myCyhShopProductService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private MyCyhShopService myCyhShopService;

    @Autowired
    private MyCyhShopCattleUserRelationService myCyhShopCattleUserRelationService;

    @Autowired
    private MyProductService myProductService;


    /**
     * 查询商家团购产品列表
     */
    @ApiOperation(value = "小程序端 查询商家团购产品",notes = "")
    @GetMapping("/web/list")
    public TableDataInfoMy weblist(Integer shopId, Integer pageNum, Integer pageSize) {
        if (pageNum ==  null && pageSize == null){
            pageNum = 1;
            pageSize = 10;
        }
        if (shopId == null){
            throw new CustomException("商家详情id为空");
        }
        PageHelper.startPage(pageNum,pageSize);
        MyCyhShopProduct  myCyhShopProduct =new MyCyhShopProduct();
        myCyhShopProduct.setShopId(shopId);
        myCyhShopProduct.setIsUp(1);//上架
        List<MyCyhShopProduct> list = myCyhShopProductService.selectMyCyhShopProductListWeb(myCyhShopProduct);
        return getDataTableMy(list);
    }


    @ApiOperation(value = "商家端 核销商家团购商品",notes = "")
    @GetMapping("/merchant/checkGoods")
    public AjaxResult edieCoupon(Integer goodsId ) {

        Integer mid = SecurityUtils.getLoginUser().getMyCyhShopCattleUser().getId();
        //查询商家端用户拥有的店
        List<Integer> list =   myCyhShopCattleUserRelationService.selectShopByMerchantUser(mid);

        MyProduct myProduct = myProductService.selectMyProductById(goodsId);
        if (myProduct == null){
            throw new CustomException("核销团购商品券不存在");
        }

        if (!list.contains(myProduct.getShopId())){
            throw new CustomException("此团购商品券属不是您管理的店");
        }

        myProduct.setIsCheck(1);
        myProduct.setCheckTime(new Date());
        myProductService.updateMyProduct(myProduct);


        //myCyhShopCouponService.updateMyCyhShopCoupon(myCyhShopCoupon);
        return AjaxResult.success("操作成功");
    }

    /**
     * 查询商家团购产品列表
     */
    @ApiOperation(value = "查询商家团购产品列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shopProduct:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyCyhShopProduct myCyhShopProduct) {

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String remark = sysUser.getRemark();
        String[] split = StringUtils.split(remark, ",");
        List<SysRole> list = roleMapper.selectRolesByUserName(sysUser.getUserName());

        List<MyCyhShop> myCyhShops = myCyhShopService.selectMyCyhShopList(null);
        Map<Integer, String> collect = myCyhShops.stream().collect(Collectors.toMap(MyCyhShop::getId, MyCyhShop::getName));

        for (SysRole sysRole : list) {
            if (sysRole.getRoleKey().equals("admin")){
                startPage();
                List<MyCyhShopProduct> list1 = myCyhShopProductService.selectMyCyhShopProductList(myCyhShopProduct);
                for (MyCyhShopProduct cyhShopProduct : list1) {
                    if (collect.containsKey(cyhShopProduct.getShopId())){
                        cyhShopProduct.setShopName(collect.get(cyhShopProduct.getShopId()));
                    }
                }
                return getDataTable(list1);
            }else if (sysRole.getRoleKey().equals("merchant")){
                List<MyCyhShopProduct> list1 = myCyhShopProductService.selectMyCyhShopProductListMe(split);
                for (MyCyhShopProduct cyhShopProduct : list1) {
                    if (collect.containsKey(cyhShopProduct.getShopId())){
                        cyhShopProduct.setShopName(collect.get(cyhShopProduct.getShopId()));
                    }
                }
                return getDataTable(list1);
            }
        }
        return null;
    }


    @ApiOperation(value = "商家端 添加团购商品",notes = "")
    @PostMapping(value = "/merchant/addProduct")
    public AjaxResult addProduct(@RequestBody MyCyhShopProduct myCyhShopProduct) {
        Integer shopId = myCyhShopProduct.getShopId();
        if (shopId == null) return AjaxResult.error("店参数不能为空");
        MyCyhShop myCyhShop = myCyhShopService.selectMyCyhShopById(shopId);
        if (myCyhShop == null){
            return AjaxResult.error("店信息不存在");
        }
        Integer mid = SecurityUtils.getLoginUser().getMyCyhShopCattleUser().getId();
        //查询商家端用户拥有的店
        List<Integer> list =   myCyhShopCattleUserRelationService.selectShopByMerchantUser(mid);
        if (!list.contains(shopId)){
            return AjaxResult.error("此店归属人不是与您");
        }
        //myCyhShopProduct.setIsUp(1);

        myCyhShopProductService.insertMyCyhShopProduct(myCyhShopProduct);
        return AjaxResult.success();
    }

    @ApiOperation(value = "商家端 查询铺下店里团购商品",notes = "")
    @GetMapping(value = "/merchant/goods")
    public AjaxResult goods(String shopIds,Integer pageNum, Integer pageSize) {
        //Integer mid = SecurityUtils.getLoginUser().getMyCyhShopCattleUser().getId();
        //查询商家端用户拥有的店
        //List<Integer> list =   myCyhShopProductService.selectByCattleUserId(mid);
        if (pageNum ==  null && pageSize == null){
            pageNum = 1;
            pageSize = 10;
        }
        if (StringUtils.isEmpty(shopIds)){
            throw new CustomException("商家详情id为空");
        }
        String[] split = StringUtils.split(shopIds, ",");

        PageHelper.startPage(pageNum,pageSize);
        MyCyhShopProduct  myCyhShopProduct =new MyCyhShopProduct();
        myCyhShopProduct.setSplit(split);
        //myCyhShopProduct.setIsUp(1);//上架
        PageHelper.startPage(pageNum,pageSize);
        List<MyCyhShopProduct> myCyhShopProducts = myCyhShopProductService.selectMyCyhShopProductListWeb(myCyhShopProduct);


        return AjaxResult.success("操作成功",myCyhShopProducts);
    }

    @ApiOperation(value = "商家端 店核销的团购商品",notes = "")
    @GetMapping(value = "/merchant/checkRecord")
    public AjaxResult checkRecord(Integer isCheck,String shopIds,Integer pageNum, Integer pageSize) {
        //Integer mid = SecurityUtils.getLoginUser().getMyCyhShopCattleUser().getId();
        //查询商家端用户拥有的店
        //List<Integer> list =   myCyhShopProductService.selectByCattleUserId(mid);
        if (pageNum ==  null && pageSize == null){
            pageNum = 1;
            pageSize = 10;
        }
        if (StringUtils.isEmpty(shopIds)) return AjaxResult.error("店参数不能为空");
        String[] split = StringUtils.split(shopIds, ",");
        MyProduct myProduct= new MyProduct();
        myProduct.setSplit(split);
        myProduct.setIsCheck(isCheck);
        PageHelper.startPage(pageNum,pageSize);
        List<MyProduct> myProducts = myProductService.selectMyProductList(myProduct);


        return AjaxResult.success("操作成功",myProducts);
    }

    @ApiOperation(value = "商家端 修改团购商品",notes = "")
    @PostMapping(value = "/merchant/editGoods")
    public AjaxResult editGoods(@RequestBody MyCyhShopProduct myCyhShopProduct) {
        Integer id = myCyhShopProduct.getId();
        if (id== null){
            return AjaxResult.error("主键参数不能为空");
        }
        myCyhShopProductService.updateMyCyhShopProduct(myCyhShopProduct);


        return AjaxResult.success("操作成功");
    }


    /**
     * 导出商家团购产品列表
     */
    @ApiOperation(value = "导出商家团购产品列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shopProduct:export')")
    @Log(title = "商家团购产品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MyCyhShopProduct myCyhShopProduct) {
        List<MyCyhShopProduct> list = myCyhShopProductService.selectMyCyhShopProductList(myCyhShopProduct);
        ExcelUtil<MyCyhShopProduct> util = new ExcelUtil<MyCyhShopProduct>(MyCyhShopProduct.class);
        return util.exportExcel(list, "shopProduct");
    }

    /**
     * 获取商家团购产品详细信息
     */
    @ApiOperation(value = "获取商家团购产品详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shopProduct:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhShopProductService.selectMyCyhShopProductById(id));
    }

    /**
     * 新增商家团购产品
     */
    @ApiOperation(value = "新增商家团购产品",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shopProduct:add')")
    @Log(title = "商家团购产品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhShopProduct myCyhShopProduct) {
        return toAjax(myCyhShopProductService.insertMyCyhShopProduct(myCyhShopProduct));
    }

    /**
     * 修改商家团购产品
     */
    @ApiOperation(value = "修改商家团购产品",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shopProduct:edit')")
    @Log(title = "商家团购产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhShopProduct myCyhShopProduct) {
        return toAjax(myCyhShopProductService.updateMyCyhShopProduct(myCyhShopProduct));
    }

    /**
     * 删除商家团购产品
     */
    @ApiOperation(value = "删除商家团购产品",notes = "")
    @PreAuthorize("@ss.hasPermi('my:shopProduct:remove')")
    @Log(title = "商家团购产品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhShopProductService.deleteMyCyhShopProductByIds(ids));
    }
}
